"use strict";

var log=require('logging');

var object=require('./object');
var util=require('./util');

var LexicalScope={};
var Method=object.create(LexicalScope);

var pp=function(o)
{
  var s='{{';
  var comma=false;
  for(key in o)
  {
    s=s+key+', ';
    comma=true;
  }

  if(comma)
  {
    s=s.substring(0,s.length-2);
  }
  s=s+'}}';

  return s;
}


var treeToScope=function(root)
{
  var scope=object.create(LexicalScope);
  return branchToScope(root, scope);
}

var branchToScope=function(node, scope)
{
  var key;
  var value;
  var subScope;
  var f;

  for(key in node)
  {
    if(node.hasOwnProperty(key))
    {
      value=node[key];

      if(util.typeOf(value)=='object')
      {
        if(value.hasOwnProperty('type') && (value.type=='method' || value.type=='flucMethod' || value.type=='native'))
        {
          f=object.slim(value, ['params', 'code', 'type']);
          f.scope=scope;
          value=f;
        }
        else
        {
          subScope=object.create(scope);
          branchToScope(value, subScope);
          value=subScope;
        }
      }

      scope[key]=value;
    }
  }

  return scope;
}

var activate=function(root, path, params)
{
//  log('activate', root, path, params);
  var parent=util.lookup(root, path);
  if(parent===undefined)
  {
    log('path not found:', path);
    return null;
  }
  else
  {
    var obj=override(parent, params);
    log('obj', obj);

    return obj;
  }
}

var override=function(parent, params)
{
  var obj=object.create(parent);
  var key;
  for(key in params)
  {
    if(params.hasOwnProperty(key))
    {
      obj[key]=params[key];
    }
  }

  return obj;
}

exports.treeToScope=treeToScope;
exports.override=override;
exports.activate=activate;
exports.pp=pp;
